package net.csdn.business.discuss.feign.aspect;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.discuss.common.constant.CommonConstants;
import net.csdn.business.discuss.common.enums.ResultCodeEnum;
import net.csdn.business.discuss.common.exception.BusinessException;
import net.csdn.business.discuss.common.utils.TokenUtil;
import net.csdn.business.discuss.feign.annotation.Inner;
import net.csdn.business.discuss.feign.config.properties.FeignAuthProperties;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import javax.servlet.http.HttpServletRequest;

/**
 * @Desc: 内部服务接口切面鉴权处理
 * @ClassName: SecurityInnerAspect
 * @Author: yourleige@163.com
 * @Date: 2022/9/26 14:36
 */
@Slf4j
@Aspect
//@Component
@RequiredArgsConstructor
public class SecurityInnerAspect {

    private final HttpServletRequest request;

    private final FeignAuthProperties feignAuthConfig;

    @SneakyThrows
    @Around("@within(inner) || @annotation(inner)")
    public Object around(ProceedingJoinPoint point, Inner inner) {
        String token = request.getHeader(CommonConstants.HEADER_TOKEN_EXTERNAL_TOKEN);
        if (!TokenUtil.verifyToken(feignAuthConfig.getAk(), feignAuthConfig.getSk(), token)) {
            log.warn("feign header token invalid! access deny");
            throw new BusinessException(ResultCodeEnum.FEIGN_UNAUTHORIZED);
        }
        // String cToken = TokenUtil.generateToken(feignAuthConfig.getAk(), feignAuthConfig.getSk());
        // if (StringUtils.isBlank(token) || !(cToken.equals(token))) {
        //     log.warn("feign header token invalid! acess deny");
        //     throw new BusinessException(ResultCodeEnum.FEIGN_UNAUTHORIZED);
        // }
        return point.proceed();
    }

}